package com.jf3q.front.controller;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.jf3q.common.exception.JfException;
import com.jf3q.common.utils.RandomUtils;
import com.jf3q.common.vo.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
@Tag(name = "短信验证码")
public class SmsController {
    @Value("${sms.serverIp}")
    private String serverIp;
    @Value("${sms.serverPort}")
    private String serverPort;
    @Value("${sms.accountSId}")
    private String accountSId;
    @Value("${sms.accountToken}")
    private String accountToken;
    @Value("${sms.appId}")
    private String appId;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/send")
    @Operation(summary = "发送短信验证码")
    public ResultVo sendSms(String imgCode, String imgKey,String phone){

        //先校验图形验证码是否正确，正确的话才发短信

        //非空判断
        if(StringUtils.isEmpty(imgKey) ||StringUtils.isEmpty(imgCode) || StringUtils.isEmpty(phone)) {
            throw new JfException(20001,"手机号必填，图形验证码必填");
        }
        //判断图片验证码
        String imgStr = stringRedisTemplate.opsForValue().get(imgKey);

        if(StringUtils.isEmpty(imgStr) || !imgStr.equals(imgCode)){
            throw new JfException(20002,"图形验证码输入错误或已超2分钟");

        }

        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String templateId= "1";
        String smsCode = RandomUtils.randomFourNum();
        String[] datas = {smsCode,"2"};

        //为了节约发短信的钱，暂时屏蔽
//        HashMap<String, Object> result = sdk.sendTemplateSMS(phone,templateId,datas);
//        if("000000".equals(result.get("statusCode"))){

            //正确发送 存入redis
            stringRedisTemplate.opsForValue().set(phone,smsCode,2, TimeUnit.MINUTES);
            return ResultVo.success("发送成功，请注意查看手机短信");
//        }else{
//            //异常返回输出错误码和错误信息
//            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
//            return ResultVo.error("发送短信失败");
//        }
    }
}
